﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Common.Communication
{
    public class SerialPortManager
    {
        /// <summary>
        /// 使用的串口对象
        /// </summary>
        public static List<SerialPort> usePorts = new List<SerialPort>();
        /// <summary>
        /// 获取设备上的COM端口集合
        /// </summary>
        /// <returns></returns>
        public static string[] GetPortNames()
        {
            return SerialPort.GetPortNames();
        }
        /// <summary>
        /// 初始化的串口对象
        /// </summary>
        /// <param name="portName"></param>
        /// <param name="baudRate"></param>
        /// <param name="parity"></param>
        /// <param name="dataBits"></param>
        /// <param name="stopBits"></param>
        /// <param name="timeout">响应超时时间</param>
        /// <returns></returns>
        public static SerialPort InitPort(string portName, int baudRate = 115200, Parity parity = Parity.None, int dataBits = 8, StopBits stopBits = StopBits.One, int timeout = 500)
        {
            //获取已实例化的串口对象，（485需共用串口）
            var port = usePorts.FirstOrDefault(o => o.PortName == portName);
            if (port != null)
            {
                //波特率变化，关闭重开
                if (port.BaudRate != baudRate)
                {
                    port.Close();
                    port.BaudRate = baudRate;
                }
                return port;
            }
            port = new SerialPort();
            port.PortName = portName;
            port.BaudRate = baudRate;
            port.DataBits = dataBits;
            port.StopBits = stopBits;
            port.Encoding = Encoding.UTF8;
            port.Parity = parity;
            port.ReadTimeout = timeout;
            port.WriteTimeout = timeout;
            //添加到使用串口列表
            usePorts.Add(port);
            return usePorts.FirstOrDefault(o => o.PortName == portName);
        }
    }
}
